import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import '@fortawesome/fontawesome-free/css/all.min.css'
import 'animate.css'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import './assets/global.css'
import router from './router'
import './styles/components.scss'
import './styles/mixins.scss'
import './styles/page-template.scss'
import './styles/unified-theme.scss'
import './styles/variables.scss'

// 修复Element UI弹窗背景
const style = document.createElement('style')
style.textContent = `
:root {
  --el-popup-modal-bg-color: transparent !important;
  --el-popup-modal-opacity: 0 !important;
}
.el-overlay {
  background-color: transparent !important;
}
.el-overlay-dialog {
  background-color: transparent !important;
}
`
document.head.appendChild(style)
// 移除了NProgress以提升性能
import type { AxiosInstance } from 'axios'
import axios from 'axios'
import 'xterm/css/xterm.css'
import { vPermission } from './directives/permission'
import './styles/dark-theme.scss'
import './styles/glass-dialog.scss'
import { clearAuthCache, getAuthToken } from './utils/cache'

// 移除了NProgress配置以提升性能

// 获取后端地址
const getBackendUrl = () => {
  // 1. 优先使用配置文件中的设置
  const globalConfig = (window as any).DEVOPS_CONFIG
  if (globalConfig?.API_BASE_URL && globalConfig.API_BASE_URL.trim()) {
    return globalConfig.API_BASE_URL.trim()
  }

  // 2. 其次使用环境变量配置
  const envApiUrl = import.meta.env.VITE_API_BASE_URL
  if (envApiUrl && envApiUrl.trim()) {
    return envApiUrl.trim()
  }

  // 3. 同服务器部署：使用当前访问的主机名
  const hostname = window.location.hostname
  const protocol = window.location.protocol
  return `${protocol}//${hostname}:8000`
}

// 配置 axios
axios.defaults.baseURL = getBackendUrl()
axios.defaults.withCredentials = true
axios.defaults.headers.common['Content-Type'] = 'application/json'

// 设置认证令牌
const storedToken = getAuthToken()
if (storedToken) {
    axios.defaults.headers.common['Authorization'] = `Token ${storedToken}`
    console.log('应用启动时已设置认证令牌')
} else {
    console.log('应用启动时未找到有效token')
}

// 请求拦截器
axios.interceptors.request.use(config => {
    // 移除了NProgress以提升性能

    const token = localStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Token ${token}`
        console.log('请求拦截器: 已添加认证令牌到请求头:', config.url, token.substring(0, 10) + '...')
    } else {
        console.warn('请求拦截器: 请求未包含认证令牌:', config.url)
        delete config.headers.Authorization
    }

    if (!config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/json'
    }

    if (!config.headers['Accept']) {
        config.headers['Accept'] = 'application/json'
    }

    console.log(`REQUEST: ${config.method?.toUpperCase()} ${config.url}`, {
        data: config.data,
        headers: { ...config.headers, Authorization: config.headers.Authorization?.substring(0, 15) + '...' }
    })

    return config
}, error => {
    // 移除了NProgress以提升性能
    console.error('请求配置错误:', error)
    return Promise.reject(error)
})

// 响应拦截器
axios.interceptors.response.use(response => {
    // 移除了NProgress以提升性能
    console.log(`RESPONSE ${response.status}:`, {
        url: response.config.url,
        data: response.data,
        headers: response.headers
    })
    return response
}, error => {
    // 移除了NProgress以提升性能

    const errorInfo = {
        url: error.config?.url || '未知URL',
        status: error.response?.status || '无响应',
        data: error.response?.data || null,
        message: error.message
    }

    console.error('响应错误:', errorInfo)

    if (error.response) {
        if (error.response.status === 401) {
            console.warn('🚫 认证失败，清理所有缓存并重新登录')

            // 使用统一的缓存清理工具
            clearAuthCache()

            if (!window.location.pathname.includes('/login') &&
                !window.location.pathname.includes('/register')) {
                router.push('/login')
            }
        } else if (error.response.status === 403) {
            console.warn('权限不足，无法访问所请求的资源')
        } else if (error.response.status === 404) {
            console.warn('请求的资源不存在')
        } else if (error.response.status >= 500) {
            console.error('服务器内部错误')
        }
    } else if (error.request) {
        console.error('未收到服务器响应，请检查网络连接和服务器状态')
    } else {
        console.error('请求配置错误:', error.message)
    }

    return Promise.reject(error)
})

console.log('🚀 开始创建Vue应用...')

// 创建应用实例
const app = createApp(App)
console.log('✅ Vue应用创建成功')

// 使用 Pinia
const pinia = createPinia()
app.use(pinia)
console.log('✅ Pinia注册成功')

// 使用路由
app.use(router)
console.log('✅ 路由注册成功')

// 使用 Element Plus
app.use(ElementPlus)
console.log('✅ Element Plus注册成功')

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
}

// 注册权限指令
app.directive('permission', vPermission)

// 全局属性
app.config.globalProperties.$http = axios as AxiosInstance

// 全局错误处理
app.config.errorHandler = (err, vm, info) => {
    console.error('Vue错误:', err, info)
}

// 挂载应用
console.log('🔧 开始挂载Vue应用到 #app...')
app.mount('#app')
console.log('✅ Vue应用挂载成功！')

// 防止拖拽文件到浏览器
document.addEventListener('dragover', (e) => {
    if (!e.target?.closest('.terminal-container')) {
        e.preventDefault()
    }
}, false)

document.addEventListener('drop', (e) => {
    if (!e.target?.closest('.terminal-container')) {
        e.preventDefault()
    }
}, false)
